const Koa = require('koa');
const app = new Koa();

// 导入配置
const {  WS_PORT } = require('./config/env');

// 初始化并启动 WebSocket 服务
const { start } = require('./tools/websocket/WebSocketServer');
start(parseInt(WS_PORT));

// // 启动 HTTP 服务
// app.listen(SERVER_PORT, () => {
//   console.log(`Server running on port ${SERVER_PORT}`);
// });

const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koajwt = require('koa-jwt')
const routers = require('./routes/index')
const {ErrorModel} = require('./utils/resModel')
const {md5, SECRET_KEY} = require('./utils/cryp')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

// logger
app.use(async (ctx, next) => {
    // await next()
    const start = new Date()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
    await next().catch((err) => {
        // console.log('next.err', err.status)
        if (err.status === 401) {
            ctx.status = 401;
            ctx.body = new ErrorModel('', '登陆过期，请重新登陆', 401)
        } else {
            ctx.body = new ErrorModel(err, '未知错误', err.status || -1)
            throw err;
        }
    })
})
/**
 * koajwt
 */

app.use(koajwt({
    secret: md5(SECRET_KEY),
    debug: true // 开启debug可以看到准确的错误信息
}).unless({ // 配置白名单
    path: [
        /^\/bone\/list/,
        /^\/api\/bone\/list/,
        /^\/user\/login/,
        /^\/api\/user\/login/,
        /^\/user\/register/,
        /^\/api\/user\/register/,
    ]
}))
// routes
// app.use(index.routes(), index.allowedMethods())
routers(app);

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
